package com.example.todo.service.impl;

import com.example.todo.mapper.KnowledgeMapper;
import com.example.todo.model.Knowledge;
import com.example.todo.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;

@Service
public class KnowledgeServiceImpl implements KnowledgeService {

    private final KnowledgeMapper knowledgeMapper;
    
    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    @Autowired
    public KnowledgeServiceImpl(KnowledgeMapper knowledgeMapper) {
        this.knowledgeMapper = knowledgeMapper;
    }

    @Override
    public List<Knowledge> findAll() {
        return knowledgeMapper.findAll();
    }

    @Override
    public Knowledge findById(Long id) {
        return knowledgeMapper.findById(id);
    }

    @Override
    public Knowledge create(Knowledge knowledge) {
        knowledgeMapper.insert(knowledge);
        return knowledge;
    }

    @Override
    public Knowledge update(Long id, Knowledge knowledge) {
        Knowledge existingKnowledge = knowledgeMapper.findById(id);
        if (existingKnowledge != null) {
            knowledge.setId(id);
            knowledgeMapper.update(knowledge);
            return knowledgeMapper.findById(id);
        }
        return null;
    }

    @Override
    public void delete(Long id) {
        Knowledge knowledge = knowledgeMapper.findById(id);
        if (knowledge != null && knowledge.getImageUrl() != null) {
            // 删除关联的图片文件
            deleteImageFile(knowledge.getImageUrl());
        }
        knowledgeMapper.delete(id);
    }

    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        // 创建上传目录（如果不存在）
        File uploadPath = new File(uploadDir);
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }
        
        // 生成唯一文件名
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + fileExtension;
        
        // 存储文件
        Path targetLocation = Paths.get(uploadDir).resolve(newFilename);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        
        // 返回完整URL路径
        return "http://localhost:8080/uploads/" + newFilename;
    }
    
    private void deleteImageFile(String imageUrl) {
        if (imageUrl == null) {
            return;
        }
        
        // 从完整URL中提取文件名
        String filename = null;
        if (imageUrl.contains("/uploads/")) {
            filename = imageUrl.substring(imageUrl.lastIndexOf("/uploads/") + "/uploads/".length());
        } else {
            return;
        }
        
        try {
            Path filePath = Paths.get(uploadDir).resolve(filename);
            Files.deleteIfExists(filePath);
        } catch (IOException e) {
            // 记录错误但不影响业务流程
            e.printStackTrace();
        }
    }
} 